package com.lizardmind.haofudoctor.ui.diagnosis.sickMan.advisory.kaifang

import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import com.linxiao.framework.activity.BaseActivity
import com.linxiao.framework.adapter.BaseAdapter
import com.linxiao.framework.util.getDataBinding
import com.linxiao.framework.util.toasts
import com.lizardmind.haofudoctor.R
import com.lizardmind.haofudoctor.databinding.ActivityKaiFangBinding
import com.lizardmind.haofudoctor.databinding.ItemTextOnlyBinding
import com.lizardmind.haofudoctor.manager.postApi
import com.lizardmind.haofudoctor.other.*
import com.lizardmind.haofudoctor.ui.diagnosis.sickMan.advisory.kaifang.addChuFang.AddChuFangActivity
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_kai_fang.*
import kotlinx.android.synthetic.main.include_title_text.*
import kotlinx.android.synthetic.main.popview_kf_sex_choose.view.*
import org.greenrobot.eventbus.Subscribe
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.json.JSONObject
import java.util.ArrayList

/**
 * 开方activity
 */
class KaiFangActivity : BaseActivity() {

    //假用户，写死的id
//    val fill_uid=1
    private val userBean by lazy { intent.getSerializableExtra("userBean") as UserBean }
    private val father_id by lazy { intent.getStringExtra("father_id") }
    private val father_type by lazy { intent.getStringExtra("father_type") }
    private val uid by lazy { intent.getStringExtra("uid") }
    private lateinit var chuFangBean:ChuFangBean
    private lateinit var popWin: PopupWindow
    private val listChuFang= arrayListOf<String>()

    private val listTaboo= arrayListOf("无","忌辛辣","忌油腻","忌生冷","忌烟酒","忌发物","忌荤腥","忌酸涩","忌刺激性事物",
            "忌光敏性食物","忌难消化食物","备孕禁服","怀孕禁服","经期停服","感冒停服","忌与西药同服")
    private var listTabooClickTag= arrayListOf<Boolean>()

    private val popViewSexChoose by lazy { LayoutInflater.from(this).inflate(R.layout.popview_kf_sex_choose,null) }
    private val adapterChuFang by lazy { BaseAdapter<String,ItemTextOnlyBinding>(R.layout.item_text_only,listChuFang) }

    val binding by lazy { getDataBinding<ActivityKaiFangBinding>(R.layout.activity_kai_fang) }
    override fun onCreatRootView(): View? {
        return binding.root
    }

    override fun onInitView(savedInstanceState: Bundle?) {
        setEvent(true)
        titleText.text="汤药"
        imgLeft.setImageResource(R.mipmap.back)
        imgLeft.onClick {
            finish()
        }

        tvSickManName.text= userBean.name
        tvSex.text=if (userBean.sex==1) "男" else "女"
        tvAge.text=userBean.age

        //性别选择
//        tvSex.onClick { showSexPopWindow() }
        popViewSexChoose.ragSexChoose.setOnCheckedChangeListener { p0, p1 ->
            popWin.dismiss()
        }
        //保存为我的常用方
        tvSaveMyCommon.onClick { saveMyCommon() }

        rvChuFang.layoutManager=GridLayoutManager(this,2)
        rvChuFang.adapter=adapterChuFang

        for (i in 0 until listTaboo.size)
            listTabooClickTag.add(false)

        for (i in listTaboo.iterator()) {
            addTagView(i)
        }

        tagLayoutTaboo.setTagClickListener(object : TagsLayout.TagClickListener{
            override fun tagClick(view: View, position: Int, clickFlag: Boolean,checkedList: ArrayList<Boolean>) {
                listTabooClickTag=checkedList
            }
        })

        //添加处方或删除处方
        tvAddChuFang.onClick {
            if (listChuFang.size==0){
                startActivity(Intent(this@KaiFangActivity,AddChuFangActivity::class.java))
            }else{
                listChuFang.clear()
                adapterChuFang.notifyDataSetChanged()
                tvSaveMyCommon.visibility=View.GONE
                val draw=ContextCompat.getDrawable(this@KaiFangActivity,R.mipmap.kf_add_fangan)
                tvAddChuFang.setCompoundDrawablesWithIntrinsicBounds(draw,null,null,null)
                tvAddChuFang.text="添加处方"
            }

        }

        tvKaiFangIsOk.onClick {
            if (TextUtils.isEmpty(etDiseaseName.text)){
                toasts("请输入病、症名")
                return@onClick
            }
            if (listChuFang.size==0){
                toasts("请添加处方")
                return@onClick
            }
            if (TextUtils.isEmpty(etTakeWay1.text)||TextUtils.isEmpty(etTakeWay2.text)||TextUtils.isEmpty(etTakeWay3.text)
                    ||etTakeWay1.text.toString()=="0"||etTakeWay2.text.toString()=="0"||etTakeWay3.text.toString()=="0"
                    ||TextUtils.isEmpty(etMoreTakeWay.text)){
            toasts("请输入帖数及用药方法")
            return@onClick
            }

            kaiFangFinish()

        }

    }

    @Subscribe
    fun getChuFangBean(evevt: ChooseChuFangEvent){
        listChuFang.clear()
        chuFangBean=evevt.bean
        val list=evevt.bean.content.split("，")
        for (i in 0 until list.size){
            listChuFang.add(list[i])
        }
        adapterChuFang.notifyDataSetChanged()
        tvSaveMyCommon.visibility=View.VISIBLE

        tvAddChuFang.text="删除处方"
        tvAddChuFang.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this,R.mipmap.kf_add_edit),null,null,null)

    }

    @Subscribe
    fun getFinishInform(event:KaiFangFinishEvent){
        finish()
    }

    private fun addTagView(str:String){
        val view=LayoutInflater.from(this).inflate(R.layout.tag_kai_fang,null)
        val textView=view.find<TextView>(R.id.tvTagKaiFang)
        textView.text=str
        tagLayoutTaboo.addView(view)
    }

    //性别选择popWindow
    private fun showSexPopWindow(){
        popWin=PopupWindow(popViewSexChoose,ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,true)
        popWin.setBackgroundDrawable(ColorDrawable(0x00000000))
        popWin.showAsDropDown(tvSex,0,30)
        popWin.setOnDismissListener {
            tvSex.text=if (popViewSexChoose.ragSexChoose.checkedRadioButtonId==R.id.rabtn_woman) "女" else "男"
        }
    }

    private fun saveMyCommon(){
        observe {
            postApi<Request<String>>(hashMapOf(
                    "action" to "add_cyyao",
                    "token" to DoctorInfo.token,
                    "type" to userBean.uid,
                    "title" to chuFangBean.title,
                    "content" to chuFangBean.content
            ), Consumer {
                toasts(it.data.toString())
            }, Action {

            },context = this)
        }
    }

    //开方完成
    private fun kaiFangFinish(){
        var avoid=""
        for (i in 0 until listTabooClickTag.size){
            if (listTabooClickTag[i]){
                avoid+=(listTaboo[i]+"，")
            }
        }

        val jsonData=JSONObject()
        jsonData.put("father_type",father_type)
        jsonData.put("father_id",father_id)
        jsonData.put("uid",uid)
        jsonData.put("fill_uid",userBean.uid)//被开方人id
        jsonData.put("symptoms",etDiseaseName.text.toString())//病症名
        jsonData.put("prescription",chuFangBean.content)//处方内容
        jsonData.put("title",chuFangBean.title)//处方名
        jsonData.put("dosage","汤药")//剂型——固定汤药
        jsonData.put("number",etTakeWay1.text.toString())//帖数
        jsonData.put("fufa",etTakeWay2.text.toString()+"~"+etTakeWay3.text.toString())//服法  eg：每日x帖，1帖分x次
        jsonData.put("fu_time",etMoreTakeWay.text.toString())//服药时间
        jsonData.put("avoid",avoid+etOtherTaboo.text.toString())//禁忌与禁口
        jsonData.put("way",etThinking.text.toString()+"")//辨证思路

        val intent=Intent(this,KaiFangSureActivity::class.java)
        val bundle=Bundle()
        bundle.putString("jsonData",jsonData.toString())
        bundle.putString("sickManData",tvSickManName.text.toString()+" "+tvSex.text.toString()+" "+tvAge.text.toString())
        intent.putExtra("kf_bundle",bundle)
        startActivity(intent)
    }
}
